package org.jeecg.modules.demo.device.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.device.entity.DeviceActivation;
import org.jeecg.modules.demo.device.entity.DeviceConfig;
import org.jeecg.modules.demo.device.service.IDeviceActivationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.device.service.IDeviceConfigService;
import org.jeecg.common.system.base.controller.XuRuiController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: device_activation
 * @Author: xurui-boot
 * @Date:   2022-01-18
 * @Version: V1.0
 */
@Api(tags="device_activation")
@RestController
@RequestMapping("/device/deviceActivation")
@Slf4j
public class DeviceActivationController extends XuRuiController<DeviceActivation, IDeviceActivationService> {
	@Autowired
	private IDeviceActivationService deviceActivationService;

	@Autowired
	private IDeviceConfigService deviceConfigService;
	
	/**
	 * 分页列表查询
	 *
	 * @param deviceActivation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "device_activation-分页列表查询")
	@ApiOperation(value="device_activation-分页列表查询", notes="device_activation-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(DeviceActivation deviceActivation,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DeviceActivation> queryWrapper = QueryGenerator.initQueryWrapper(deviceActivation, req.getParameterMap());
		Page<DeviceActivation> page = new Page<DeviceActivation>(pageNo, pageSize);
		String status=req.getParameter("status");
		SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
		String currentTime = sformat.format(new Date());
		if("3".equals(status)){//试用过期
			queryWrapper.lt("trial_end_time",currentTime);
		}else if("4".equals(status)){//激活过期
			queryWrapper.lt("activation_end_time",currentTime);
		}else {
			if(status!=null){
				queryWrapper.eq("use_status",status);
			}

		}
		IPage<DeviceActivation> pageList = deviceActivationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	 @GetMapping(value = "/deviceStatus")
	 public Result<Map<String,Object>> deviceStatus(@RequestParam(name="deviceId",required=true) String deviceId,@RequestParam(name="terminalType",required=true) String terminalType) {
		 Result<Map<String,Object>> result = new Result<>();
		 //Result<DeviceActivation> result = new Result<DeviceActivation>();
		 Map<String,Object> resMap = new HashMap<String,Object>();
		 DeviceActivation deviceActivation = deviceActivationService.deviceStatus(deviceId);
		 DeviceConfig deviceConfig=deviceConfigService.quertyConfigInfo();
		 if(deviceActivation==null) {
		 	if(deviceConfig==null){
				result.error500("请先配置设备公用配置信息");
			}else{
				DeviceActivation deviceActive=new DeviceActivation();
				Date trialStart = DateUtil.parse(DateUtil.today());
				Date trialEnd = DateUtil.offsetDay(trialStart,deviceConfig.getTrialDuration());
				deviceActive.setDeviceId(deviceId);
				deviceActive.setUseStatus("1");
				deviceActive.setTrialDuration(deviceConfig.getTrialDuration());
				deviceActive.setTrialStartTime(trialStart);
				deviceActive.setTrialEndTime(trialEnd);
				deviceActive.setActivationDuration(deviceConfig.getActivationDuration());
				deviceActive.setAndroidCost(deviceConfig.getAndroidCost());
				deviceActive.setIosCost(deviceConfig.getIosCost());
				deviceActivationService.save(deviceActive);

				resMap.put("deviceActive",deviceActive);
				resMap.put("terminalType",terminalType);
				result.setResult(resMap);
				result.setMessage("已开通试用功能");
				result.setSuccess(true);
			}

		 }else {
		 	//判断 使用状态，未试用根据设备Id进行更新试用信息，已试用试用是否到期，如果到期提示试用已到期，请激活，否则在试用中，已激活，判断激活是否到期。
			 if("0".equals(deviceActivation.getUseStatus())){//未试用
			 	if(deviceActivation.getTrialDuration()==null){//没有时长配置
					Date trialStart = DateUtil.parse(DateUtil.today());
					Date trialEnd = DateUtil.offsetDay(trialStart,deviceConfig.getTrialDuration());
					deviceActivation.setUseStatus("1");
					deviceActivation.setTrialDuration(deviceConfig.getTrialDuration());
					deviceActivation.setTrialStartTime(trialStart);
					deviceActivation.setTrialEndTime(trialEnd);
					deviceActivation.setActivationDuration(deviceConfig.getActivationDuration());
					deviceActivation.setAndroidCost(deviceConfig.getAndroidCost());
					deviceActivation.setIosCost(deviceConfig.getIosCost());
					deviceActivationService.saveOrUpdate(deviceActivation);
				}else{//有时长配置修改 使用状态、试用开始结束时间
					Date trialStart = DateUtil.parse(DateUtil.today());
					Date trialEnd = DateUtil.offsetDay(trialStart,deviceActivation.getTrialDuration());
					deviceActivation.setUseStatus("1");
					deviceActivation.setTrialStartTime(trialStart);
					deviceActivation.setTrialEndTime(trialEnd);
					deviceActivationService.saveOrUpdate(deviceActivation);
				}
				 resMap.put("deviceActive",deviceActivation);
				 resMap.put("terminalType",terminalType);
				 result.setResult(resMap);
				 result.setMessage("已开通试用功能");
				 result.setSuccess(true);
			 }else if("1".equals(deviceActivation.getUseStatus())){//已试用
				 SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
				 String trialEndTime = sformat.format(new Date());
				int count=deviceActivationService.countTrialEnd(trialEndTime,"");//如果为0没有到期 1已经到期
				 if(count>0){
					 resMap.put("deviceActive",deviceActivation);
					 resMap.put("terminalType",terminalType);
					 result.setResult(resMap);
					 result.setMessage("试用已到期，请激活后使用");
					 result.setSuccess(true);
				 }else{
					 resMap.put("deviceActive",deviceActivation);
					 resMap.put("terminalType",terminalType);
					 result.setResult(resMap);
					 result.setMessage("正在试用中");
					 result.setSuccess(true);
				 }

			 }else if("2".equals(deviceActivation.getUseStatus())){//已激活
				 SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
				 String activationEndTime = sformat.format(new Date());
				 int count=deviceActivationService.countTrialEnd("",activationEndTime);//如果为0没有到期 1已经到期
				 if(count>0){
					 resMap.put("deviceActive",deviceActivation);
					 resMap.put("terminalType",terminalType);
					 result.setResult(resMap);
					 result.setMessage("激活已到期，请激活后使用");
					 result.setSuccess(true);
				 }else{
					 resMap.put("deviceActive",deviceActivation);
					 resMap.put("terminalType",terminalType);
					 result.setResult(resMap);
					 result.setMessage("正在使用");
					 result.setSuccess(true);
				 }

			 }

		 }
		 return result;
	 }



	 @AutoLog(value = "device_activation-编辑")
	 @ApiOperation(value="device_activation-编辑", notes="device_activation-编辑")
	 @PostMapping(value = "/batchConfig")
	 public Result<?> batchConfig(@RequestBody JSONObject jsonObject) {
		String message="";
		 String ids = jsonObject.getString("ids");
		 String customerId = jsonObject.getString("customerId");
		 Integer trialDuration=jsonObject.getIntValue("trialDuration");
		 Integer activationDuration=jsonObject.getIntValue("activationDuration");
		 BigDecimal androidCost=jsonObject.getBigDecimal("androidCost");
		 BigDecimal iosCost=jsonObject.getBigDecimal("iosCost");
		 if(!"".equals(customerId)){
			 List<DeviceActivation> list=deviceActivationService.getCustomerList(customerId);
			 if(list.size()>0){
				 for(DeviceActivation deviceActivation :list){
					 deviceActivation.setTrialDuration(trialDuration);
					 deviceActivation.setActivationDuration(activationDuration);
					 deviceActivation.setAndroidCost(androidCost);
					 deviceActivation.setIosCost(iosCost);

					 deviceActivationService.updateById(deviceActivation);
				 }
			 }
		 }
		if(!"".equals(ids)){
			String[] arr = ids.split(",");
			for (String id : arr) {
				DeviceActivation deviceActivation=deviceActivationService.getById(id);
				if(deviceActivation!=null){
					if(deviceActivation.getUseStatus().equals("0")&& deviceActivation.getTrialDuration()==null){
						deviceActivation.setTrialDuration(trialDuration);
						deviceActivation.setActivationDuration(activationDuration);
						deviceActivation.setAndroidCost(androidCost);
						deviceActivation.setIosCost(iosCost);
						deviceActivationService.updateById(deviceActivation);
					}

				}
			}
		}

		 return Result.OK("批量配置成功!");
	 }
	
	/**
	 *   添加
	 *
	 * @param deviceActivation
	 * @return
	 */
	@AutoLog(value = "device_activation-添加")
	@ApiOperation(value="device_activation-添加", notes="device_activation-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody DeviceActivation deviceActivation) {
		deviceActivationService.save(deviceActivation);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param deviceActivation
	 * @return
	 */
	@AutoLog(value = "device_activation-编辑")
	@ApiOperation(value="device_activation-编辑", notes="device_activation-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody DeviceActivation deviceActivation) {
		deviceActivationService.updateById(deviceActivation);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "device_activation-通过id删除")
	@ApiOperation(value="device_activation-通过id删除", notes="device_activation-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		//deviceActivationService.removeById(id);
		deviceActivationService.updateDelFlag(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "device_activation-批量删除")
	@ApiOperation(value="device_activation-批量删除", notes="device_activation-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.deviceActivationService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "device_activation-通过id查询")
	@ApiOperation(value="device_activation-通过id查询", notes="device_activation-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		DeviceActivation deviceActivation = deviceActivationService.getById(id);
		if(deviceActivation==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(deviceActivation);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param deviceActivation
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DeviceActivation deviceActivation) {
        return super.exportXls(request, deviceActivation, DeviceActivation.class, "device_activation");
    }


	 @RequestMapping(value = "batchImport", method = RequestMethod.POST)
	 public Result<?> batchImport(@RequestBody JSONObject jsonObject) {
		 String fileUrl = jsonObject.getString("fileUrl");
		 String customerId = jsonObject.getString("customerId");
		System.out.println(fileUrl);
		System.out.println(customerId);
		String path="D:\\upFiles\\"+fileUrl;
		 File excelFile = new File(path);
		 try {
			 FileInputStream is = new FileInputStream(excelFile); //文件流
			 Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的

			 StringBuffer sb = new StringBuffer();
			 //工作表
			 Sheet sheet = workbook.getSheetAt(0);
			 int rowCount = sheet.getLastRowNum(); //获取总行数
			 sb.append(rowCount);
			 sb.append("行，消息提示:");
			 //遍历每一行
			 for (int r = 0; r < rowCount; r++) {
				String deviceId=null;
				 Row row = sheet.getRow(r+1);
				 if (row == null) {
					 break;
				 }

					 Cell cell = row.getCell(0);
				 if(cell!=null){
					 //在读取单元格内容前,设置所有单元格中内容都是字符串类型
					 cell.setCellType(CellType.STRING);

					 //按照字符串类型读取单元格内数据
					 deviceId = cell.getStringCellValue();

					 /*在这里可以对每个单元格中的值进行二次操作转化*/

					 System.out.print(deviceId + "    ");
				 }

				 if(deviceId==null){
					 sb.append("第");
					 sb.append(r+1);
					 sb.append("行，设备ID:为空或者不存在，请重新填写后进行重新导入!");
				 }else {
					 DeviceActivation activation = deviceActivationService.deviceStatus(deviceId);
					 if(activation==null){
						 DeviceActivation deviceActivation=new DeviceActivation();
						 deviceActivation.setCustomerId(customerId);
						 deviceActivation.setUseStatus("0");
						 deviceActivation.setDeviceId(deviceId);
						 deviceActivationService.save(deviceActivation);
						 sb.append("第");
						 sb.append(r+1);
						 sb.append("行，正确!");
					 }else{
						 sb.append("第");
						 sb.append(r+1);
						 sb.append("行，设备ID:");
						 sb.append(deviceId);
						 sb.append("该设备ID已经存在不能重复导入!");
					 }
				 }


				 System.out.println();
			 }

			 return Result.ok("文件导入成功！数据行数:" + sb.toString());
		 } catch (FileNotFoundException e) {
			 e.printStackTrace();
			 return Result.error("文件导入失败:"+e.getMessage());
		 } catch (IOException e) {
			 e.printStackTrace();
			 return Result.error("文件导入失败:"+e.getMessage());
		 }
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       // return super.importExcel(request, response, DeviceActivation.class);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<DeviceActivation> listDeviceActivation = ExcelImportUtil.importExcel(file.getInputStream(), DeviceActivation.class, params);

				deviceActivationService.saveBatch(listDeviceActivation);
				return Result.ok("文件导入成功！数据行数:" + listDeviceActivation.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
    }

}
